<template>
    <div class="content">
        <div class="top">
            <van-image width="100%" height="6rem" fit="cover" :src="shopInfo.s_picture" />
        </div>
        <div class="arrow" @click="onClickLeft">
            <van-icon name="arrow-left" />
        </div>
        <div class="center">
            <div class="pic">
                <van-image width="3rem" height="3rem" fit="cover" :src="shopInfo.s_picture" />
            </div>
            <div class="first">
                <div class="name">{{ shopInfo.s_name }}</div>
                <div class="status">{{ shopInfo.s_status == 1 ? '营业中' : '休息' }}</div>
                <div class="sixcode">{{ sixcode }}</div>
            </div>
            <div class="second">
                <div class="comment">{{ shopInfo.s_comment }}分</div>
                <div class="owner">店主:{{ shopInfo.s_owner }}</div>
                <div class="time">自{{ shopInfo.s_create_time }}</div>
            </div>
            <div class="third">
                <div class="van-ellipsis introduction">{{ shopInfo.s_introduction }}</div>
            </div>
        </div>
        <div class="main">
            <div class="siderbar" ref="container">
                <van-sticky :offset-top="0" :container="container">
                    <van-sidebar v-model="active" @change="onChange">
                        <van-sidebar-item class="siderbarItem" v-for="item in siderbarList" :title="item.title"
                            :badge="item.count == 0 ? '' : item.count" />
                    </van-sidebar>
                </van-sticky>
            </div>
            <div class="right_content">
                <van-index-bar :index-list="indexList" ref="siderbar">
                    <div v-for="item in siderbarList">
                        <van-index-anchor :index="item.title">{{ item.title }}</van-index-anchor>
                        <div v-for="item1 in item.commodity">
                            <lazy-component>
                                <van-card style="font-size: 1rem;" :price="item1.mprice" :desc="item1.mintro"
                                    :title="item1.mname" :thumb="item1.mpic" :lazy-load="true">
                                    <template #tags>
                                        <van-tag plain type="danger">月销{{ item1.msales }}</van-tag>
                                        <van-tag plain type="warning">库存{{ item1.mstock }}</van-tag>
                                    </template>
                                    <template #footer>
                                        <van-stepper v-model="item1.num" theme="round" button-size="18" disable-input
                                            allow-empty default-value="0" :show-minus="item1.num == 0 ? false : true"
                                            min="0" @change="settlement" :show-input="item1.num == 0 ? false : true" />
                                    </template>
                                </van-card>
                            </lazy-component>
                        </div>
                    </div>
                </van-index-bar>
            </div>
        </div>
        <div class="bottom">
            <van-image width="100%" height="6rem" fit="cover" src="https://img.cwiyc.top/reachbottom.webp" />
            <div class="text">
                到底啦！！！
            </div>
        </div>
        <div class="bbb">
            <van-submit-bar :price="total" button-text="结算" @submit="throttle(onSubmit, 1000)">
                <van-badge :content="amount" max="99">
                    <van-image @click="showbox" width="3rem" height="3rem" fit="cover"
                        src="https://img.cwiyc.top/box.jpg" />
                </van-badge>
            </van-submit-bar>
        </div>
        <div class="pop">
            <van-action-sheet v-model:show="show" title="已选商品">
                <van-cell :title="item.mname" v-for="item in choosedList">
                    <template #right-icon>
                        <van-stepper v-model="item.num" theme="round" button-size="18" disable-input allow-empty
                            default-value="0" :show-minus="item.num == 0 ? false : true" min="0" @change="settlement"
                            :show-input="item.num == 0 ? false : true" />
                        <div style="position:absolute;top:2rem;left: 16rem;font-size: 13px;font-weight: 500;color: tomato;">
                            ￥{{ (item.mprice * item.num).toFixed(2) }}</div>
                        <van-image width="2.5rem" height="2.5rem" fit="cover" :src="item.mpic" />
                    </template>
                </van-cell>
                <van-cell>
                    <template #right-icon>
                        <div>合计:￥{{ total / 100 }}</div>
                        <van-button @click="clearBox" style="position: absolute; right:1rem;" icon="delete-o" type="plain"
                            size="mini">清空</van-button>
                    </template>
                </van-cell>
            </van-action-sheet>
        </div>
        <van-overlay :show="overlayshow" @click="overlayshow = false">
            <div class="wrapper" @click.stop>
                <div class="block">
                    请先选择店铺
                </div>
            </div>
        </van-overlay>
    </div>
</template>
  
<script setup>
import { ref, onUnmounted } from 'vue'
import { getCurrentInstance } from '@vue/runtime-core';
import { dateFormat } from '@/utils/time'
import throttle from '~~/utils/throttle';

const active = ref(0);
const onClickLeft = () => history.back();
const shopInfo = ref([]);
const siderbarList = ref([]);
const indexList = ref([]);
const indexLists = ref([])
const index = ref(0)
const total = ref(0)
const amount = ref(0)
const show = ref(false);
const choosedList = ref([]);
const overlayshow = ref(false)
const router = useRouter()
const currentInstance = getCurrentInstance()
const container = ref(null);
const sixcode = ref('')
const shopCodeCookie = useCookie('shopcode')
const userInfoCookie = useCookie('userInfo')
const userStateCurrentShop = useUserStateCurrentShop()
const userStateShopInfo = useUserStateShopInfo()
const userStateSiderbarList = useUserStateSiderbarList()
const userStateCartTotal = useUserStateCartTotal()
const userStateCartAmount = useUserStateCartAmount()
const userStateCartChoosedList = useUserStateCartChoosedList()
function init() {
    // console.log(userStateShopInfo.value,userStateCurrentShop.value,shopCodeCookie.value)
    if (userStateShopInfo.value && (userStateCurrentShop.value == shopCodeCookie.value)) {
        getData()
    }
    else {
        let code = shopCodeCookie.value
        let paramsCode = router.currentRoute._value.query.code
        if (!paramsCode && !code) {
            overlayshow.value = true
            setTimeout(() => {
                history.back()
            }, 1000)
            return;
        }
        if (paramsCode) {
            sixcode.value = paramsCode
            findShop(sixcode.value)
            findMeal(sixcode.value)
        }
        else {
            sixcode.value = code
            findShop(sixcode.value)
            findMeal(sixcode.value)
        }
    }
}
init()
onUnmounted(() => {
    saveData()
})
function saveData() {
    userStateShopInfo.value = shopInfo.value
    userStateSiderbarList.value = siderbarList.value
    userStateCartTotal.value = total.value
    userStateCartAmount.value = amount.value
    userStateCartChoosedList.value = choosedList.value
    userStateCurrentShop.value = shopCodeCookie.value
}
function getData() {
    shopInfo.value = userStateShopInfo.value
    siderbarList.value = userStateSiderbarList.value
    total.value = userStateCartTotal.value
    amount.value = userStateCartAmount.value
    choosedList.value = userStateCartChoosedList.value
    sixcode.value = userStateCurrentShop.value
}
async function findShop(sixcode) {
    let shop = {
        ssixcode: sixcode
    }
    const { data } = await myUseFetch('/getshop', { method: 'post', body: shop })
    let res = data.value
    if (res.code == -1) {
        console.log(res)
    } else if (res.code == 0) {
        shopInfo.value = {
            s_name: res.data.sname,
            s_create_time: res.data.screatetime,
            s_picture: res.data.spicture,
            s_comment: res.data.scomment,
            s_introduction: res.data.sintroduction,
            s_status: res.data.sstatus,
            s_owner: res.data.sowner
        }
        // findMeal(res.data.sid)
    }
}
async function findMeal(code) {
    // let meal = {
    //     msid: msid
    // }
    const { data } = await myUseFetch(`/getmealbycode?code=${code}`, { method: 'get'})
    let res = data.value
    if (res.code == -1) {
        console.log(res)
    } else if (res.code == 0) {
        let oldVa = res.data[0].mtype
        let oldarr = []
        res.data.forEach((item, index) => {
            if (item.mtype != oldVa) {
                siderbarList.value.push({
                    title: oldVa,
                    count: 0,
                    commodity: oldarr
                })
                oldarr = []
            }
            if (index == res.data.length - 1 && item.mtype == oldVa) {
                oldarr.push(item)
                siderbarList.value.push({
                    title: oldVa,
                    count: 0,
                    commodity: oldarr
                })
                oldarr = []
            }
            if (index == res.data.length - 1 && item.mtype != oldVa) {
                oldarr.push(item)
                siderbarList.value.push({
                    title: item.mtype,
                    count: 0,
                    commodity: oldarr
                })
                oldarr = []
            }
            oldarr.push(item)
            oldVa = item.mtype
        })
        siderbarList.value.forEach(item => {
            indexLists.value.push(item.title)
        })
    }
}

const onChange = (index1) => {
    if (process.env.NODE_ENV == 'development')
        currentInstance.ctx.$refs.siderbar.scrollTo(indexLists.value[index1])
    else {
        currentInstance.refs.siderbar.scrollTo(indexLists.value[index1])
    }
};
const settlement = () => {
    total.value = 0
    amount.value = 0
    let temp = 0
    siderbarList.value.forEach(item1 => {
        temp = 0
        item1.commodity.forEach(item2 => {
            if (item2.num != 0) {
                total.value += item2.num * item2.mprice * 100
                amount.value += item2.num
                temp += item2.num
            }
        })
        item1.count = temp
    });
    setTimeout(() => {
        bianli()
    }, 100);
}
const clearBox = () => {
    choosedList.value = []
    siderbarList.value.forEach(item1 => {
        item1.commodity.forEach(item2 => {
            item2.num = 0
        })
    });
}
const showbox = () => {
    show.value = !show.value
    bianli()
}
function bianli() {
    choosedList.value = []
    siderbarList.value.forEach(item1 => {
        item1.commodity.forEach(item2 => {
            if (item2.num != 0) {
                choosedList.value.push(item2)
            }
        })
    });
}
const onSubmit = async () => {
    let date = new Date()
    let order = {
        orealid: (new Date()).getTime() + 7758258,
        ocreatetime: dateFormat("YYYY-mm-dd HH:MM:SS", date),
        ototalprice: total.value / 100,
        ostatus: 0,
        ouid: userInfoCookie.value.uid
    }
    console.log(order)
    const { data } = await myUseFetch('/createorder', { method: 'post', body: order })
    let res = data.value
    if (res.code == -1) {
        console.log(res)
    } else if (res.code == 0) {
        // console.log(res)
        let final = []
        choosedList.value.forEach(item => {
            final.push({
                odmid: item.mid,
                odmcount: item.num,
                odoid: res.data.oid
            })
        })
        const { data } = await myUseFetch('/createod', { method: 'post', body: final })
        let ress = data.value
        if (ress.code == -1) {
            console.log(ress)
        } else if (ress.code == 0) {
            // console.log(ress)
            clearBox()
            setTimeout(() => {
                router.push("/order")
            }, 1000)
        }
    }
}

</script>
  
<style scoped lang="scss">
.content {
    height: 100%;
    background-color: rgb(240, 236, 236);

    .arrow {
        position: absolute;
        color: #fff;
        top: 1rem;
        left: 0.5rem;
        font-size: larger;
    }

    .center {
        width: 90vw;
        height: 5.6rem;
        border-radius: 0.8rem;
        position: relative;
        top: -2.8rem;
        margin: 0 auto;
        background-color: #fff;

        // padding: 5px;
        .pic {
            position: absolute;
            height: 50%;
            right: 0.8rem;
            top: 0.8rem;
            border-radius: 0.3rem;
            overflow: hidden;
        }

        .first {
            display: flex;

            .name {
                font-size: 1rem;
                padding: 8px 12px 0 12px;
                font-weight: bold;
            }

            .status {
                color: #fff;
                background-color: rgb(42, 176, 230);
                border-radius: 8px;
                align-self: center;
                padding: 0 2px 0 2px;
                font-size: 0.8rem;
                margin-top: 8px;
            }

            .sixcode {
                position: absolute;
                right: 5rem;
                top: 0.8rem;
                font-weight: bold;
            }
        }

        .second {
            display: flex;

            .comment {
                color: rgb(232, 116, 23);
                font-size: 0.8rem;
                font-weight: bold;
                padding: 5px 0 5px 12px;
            }

            .owner {
                color: rgb(167, 152, 140);
                font-size: 0.8rem;
                font-weight: bold;
                padding: 5px 0 5px 12px;
            }

            .time {
                color: rgb(167, 152, 140);
                font-size: 0.8rem;
                font-weight: bold;
                padding: 5px 0 5px 12px;
            }
        }

        .third {
            .introduction {
                font-size: 0.8rem;
                padding: 3px 0 5px 12px;
                color: rgb(137, 135, 135);
            }
        }
    }

    .main {
        position: relative;
        display: flex;
        width: 100%;
        top: -2.7rem;

        .siderbar {
            // width: 21%;
            position: sticky;
            top: 3rem;
            height: 85vh;
        }

        .right_content {
            width: 100%;
            position: relative;
            left: 1%;
            margin-right: 2%;
            // top: -18rem;
        }
    }

    .bottom {
        position: relative;
        top: -2.7rem;

        .text {
            position: absolute;
            font-weight: bold;
            bottom: 5rem;
            left: 50%;
            transform: translate(-50%);
        }
    }

    .bbb {

        .badge {
            position: absolute;
            bottom: 2.5rem;
            right: 3rem;
        }
    }

    .wrapper {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 100%;

        .block {
            // width: 120px;
            // height: 120px;
            // background-color: #fff;
            color: #fff;
        }
    }

}
</style>